#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
代理核心模块

负责管理和协调各个AI模型的加载和使用，以及处理机器人的状态管理和决策。
"""

import os
import openai
from typing import Dict, Any, Optional, List
import json
import threading
from datetime import datetime
import asyncio
import time

from .intent_processor import IntentProcessor
from .action_planner import ActionPlanner
from .sensor_fusion import SensorFusion
from .mcp_interface import MCPInterface


class AgentCore:
    """代理核心类"""

    def __init__(
        self, api_key: Optional[str] = None, host: str = "0.0.0.0", port: int = 9000
    ):
        """
        初始化代理核心

        Args:
            api_key: OpenAI API密钥，如果为None则从环境变量获取
            host: MCP服务器主机地址
            port: MCP服务器端口
        """
        self.api_key = api_key or os.getenv("OPENAI_API_KEY")
        if not self.api_key:
            raise ValueError("未提供API密钥且环境变量OPENAI_API_KEY未设置")

        # 初始化OpenAI
        openai.api_key = self.api_key
        openai.api_base = "https://dashscope.aliyuncs.com/compatible-mode/v1"

        # 初始化子模块
        self.intent_processor = IntentProcessor(self.api_key)
        self.action_planner = ActionPlanner(self.api_key)
        self.sensor_fusion = SensorFusion()

        # 初始化MCP接口
        self.mcp_interface = MCPInterface(self, host, port)

        # 状态管理
        self.current_state = {
            "status": "idle",
            "last_action": None,
            "last_update": datetime.now(),
            "sensor_data": {},
            "error_count": 0,
        }

        # 运行标志
        self._running = False
        self._process_thread = None

    async def start(self):
        """启动代理核心"""
        if self._running:
            return

        self._running = True
        # 启动MCP接口
        await self.mcp_interface.start()
        # 启动处理线程
        self._process_thread = threading.Thread(target=self._process_loop)
        self._process_thread.start()

        logger.info("代理核心已启动")

    async def stop(self):
        """停止代理核心"""
        if not self._running:
            return

        self._running = False
        # 停止MCP接口
        await self.mcp_interface.stop()
        # 等待处理线程结束
        if self._process_thread:
            self._process_thread.join()

        logger.info("代理核心已停止")

    def _process_loop(self):
        """处理循环"""
        while self._running:
            try:
                # 更新传感器数据
                self._update_sensor_data()
                # 广播状态
                asyncio.run(self.mcp_interface.broadcast_state())
                # 处理意图
                self._process_intent()
                # 规划动作
                self._plan_action()
                # 执行动作
                self._execute_action()
                # 更新状态
                self._update_state()

                # 短暂休眠以避免CPU过载
                time.sleep(0.1)
            except Exception as e:
                logger.error(f"处理循环出错: {e}")
                self.current_state["error_count"] += 1
                time.sleep(1)  # 出错后等待较长时间

    def _update_sensor_data(self):
        """更新传感器数据"""
        self.current_state["sensor_data"] = self.sensor_fusion.get_fused_data()

    def _process_intent(self):
        """处理意图"""
        # TODO: 实现意图处理逻辑
        pass

    def _plan_action(self):
        """规划动作"""
        # TODO: 实现动作规划逻辑
        pass

    def _execute_action(self):
        """执行动作"""
        # TODO: 实现动作执行逻辑
        pass

    def _update_state(self):
        """更新状态"""
        self.current_state["last_update"] = datetime.now()

    def get_state(self) -> Dict[str, Any]:
        """
        获取当前状态

        Returns:
            Dict[str, Any]: 当前状态字典
        """
        return self.current_state.copy()

    def process_command(self, command: str) -> Dict[str, Any]:
        """
        处理用户命令

        Args:
            command: 用户命令字符串

        Returns:
            Dict[str, Any]: 处理结果
        """
        try:
            # 理解意图
            intent = self.intent_processor.process(command)

            # 规划动作
            action_plan = self.action_planner.plan(intent)

            # 执行动作
            result = self._execute_action_plan(action_plan)

            return {
                "status": "success",
                "intent": intent,
                "action_plan": action_plan,
                "result": result,
            }

        except Exception as e:
            return {"status": "error", "error": str(e)}

    def _execute_action_plan(self, action_plan: Dict[str, Any]) -> Dict[str, Any]:
        """
        执行动作计划

        Args:
            action_plan: 动作计划字典

        Returns:
            Dict[str, Any]: 执行结果
        """
        # TODO: 实现动作计划执行逻辑
        return {"status": "not_implemented"}

    def update_state(self, new_state: Dict[str, Any]):
        """更新状态"""
        self.current_state.update(new_state)
        self.current_state["last_update"] = datetime.now()

    def update_action_result(self, result: Dict[str, Any]):
        """更新动作执行结果"""
        self.current_state["last_action"] = result
        self.current_state["last_update"] = datetime.now()
